<template>
  <section class="container">
    <input
      id="image"
      ref="input"
      type="file"
      style="display: none;"
      accept="image/png, image/jpeg, image/gif, image/jpg"
      @change="chooseFile"
    >
    <el-button v-if="!iconClass" type="primary" size="mini" @click="handleModify">
      更换
    </el-button>
    <i v-if="iconClass" :class="['iconfont', iconClass]" @click="handleModify" />
  </section>
</template>

<script>
export default {
  props: {
    iconClass: {
      type: String,
      default: () => ''
    },
    url: {
      type: String,
      default: () => ''
    },
    fileSize: {
      type: Number,
      default: () => 2100000 // 上传图片最大值(单位字节)（ 2 M = 2097152 B ）
    }
  },
  data() {
    return {
      base64Str: ''
    }
  },
  computed: {
    userData() {
      return this.$store.state.user.userData
    }
  },
  methods: {
    handleModify() {
      this.$refs.input.click()
    },
    chooseFile() {
      const reader = new FileReader()
      const file = this.$refs.input.files[0]
      if (file) {
        if (file.size && file.size > this.fileSize) {
          this.fileSizeExceed()
          return
        }
        // 将文件以Data URL形式读入页面
        reader.readAsDataURL(file)
        reader.onload = () => {
          // var ImgFileSize = reader.result.substring(reader.result.indexOf(",") + 1).length;//截取base64码部分（可选可不选，需要与后台沟通）
          this.uploadCroppedImage(reader.result)
        }
      }
    },
    fileSizeExceed() {
      this.$alert(`文件大于${parseInt(this.fileSize / 1048570)}M，请重新选择`, '提示', {
        confirmButtonText: '确定',
        type: 'warning',
        lockScroll: false
      })
    },
    async uploadCroppedImage(base64Data) {
      const params = {
        base64Data
      }
      const data = await this.$request({
        context: this,
        method: 'post',
        url: this.url,
        params
      })
      if (!data) return
      // 如果需要服务器返回的图片地址，监听此方法即可
      this.$emit('imgUrl', data)
    }
  }
}
</script>

<style lang="scss" scoped>
  @import "~@/assets/css/public";

  .container {
    cursor: pointer;
    // opacity: 0;
    // z-index: -1;

    .iconfont {
      font-size: 18px;
      color: #fff;
    }
  }
</style>
